package trucaso;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataOutputStream;
import java.io.IOException;

import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class ChatPane extends JPanel {
	protected JTextField in;
	protected JTextArea out;
	protected JScrollPane scrollPane;
	protected DataOutputStream streamOut;
	
	protected ChatPane(DataOutputStream so) {
		super();
		setLayout(new BorderLayout());
		out = new JTextArea(10,80) {
			  public void append(String str) {
		          super.append('\n'+str);
		               setCaretPosition(getDocument().getLength());
		      	}
		     };
		scrollPane = new JScrollPane(out,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
		in = new JTextField();
		
		streamOut = so;
		
		scrollPane.setAutoscrolls(true);
		scrollPane.setWheelScrollingEnabled(true);
		out.setEditable(false);
		out.append("This is Truco! o algo...\nHave Fun!\nhttp://sourceforge.net\n");
		
		add(scrollPane, BorderLayout.CENTER);
		add(in, BorderLayout.SOUTH);
		
		out.setBackground(new Color(229,212,153));
		in.setBackground(out.getBackground());
		
		
		in.addActionListener(new ActionListener(){
	  	  public void actionPerformed(ActionEvent evt){
	  		  if(in.getText().length()>0) {
	  			  try {
	  				 try{ 
	  					 streamOut.writeUTF("<:"+in.getText());
	  				     streamOut.flush();
	  				 }catch(NullPointerException npex) {
	  					out.append(":>"+in.getText());
		  				 in.setText("");
	  				 }
	  				 out.append(":>"+in.getText());
	  				 in.setText("");
	  		  	  }catch(IOException ioe) {
	  		  		  putMessage("Sending Error: "+ioe.getMessage());
	  		  	  }
	  		  }
	  	  }
		});

	}
	
	protected void setOutputStream(DataOutputStream out) {
		streamOut = out;
	}
	
	protected void putMessage(String msg) {
		out.append(msg);
	}
		
}
